package com.wwwarehouse.usercenter.fragment.chain_triangles;

import android.app.Dialog;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.wei.android.lib.fingerprintidentify.FingerprintIdentify;
import com.wei.android.lib.fingerprintidentify.base.BaseFingerprint;
import com.wwwarehouse.common.activity.base.BaseApplication;
import com.wwwarehouse.common.activity.base.BaseFragment;
import com.wwwarehouse.common.bean.response.CardDeskFunctionResponseBean;
import com.wwwarehouse.common.bean.response.CommonClass;
import com.wwwarehouse.common.constant.Constant;
import com.wwwarehouse.common.custom_widget.ClearEditText;
import com.wwwarehouse.common.eventbus_event.BackListenerEvent;
import com.wwwarehouse.common.http.NoHttpUtils;
import com.wwwarehouse.common.tools.DialogTools;
import com.wwwarehouse.common.tools.LogUtils;
import com.wwwarehouse.common.tools.rsa.Base64Utils;
import com.wwwarehouse.common.tools.rsa.RSAUtil;
import com.wwwarehouse.usercenter.R;
import com.wwwarehouse.usercenter.constant.UserCenterConstant;

import java.util.HashMap;
import java.util.Map;

import de.greenrobot.event.EventBus;


/**
 * Created by xiaoke.ni on 2017/8/31.
 */
@Route(path = UserCenterConstant.PATH_TC_AM_FRAGMWNT)
public class TCAuthenticationFragment extends BaseFragment implements View.OnClickListener {

    private View mView;
    private RelativeLayout mMainRl;
    private ImageView mIvFingerUnlock;
    private TextView mTvFingerUnlock;
    private ClearEditText mEtWeight;
    private Button mSureBtn;

    private FingerprintIdentify mFingerprintIdentify;
    private DialogTools dialogTools;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        mView = View.inflate(getActivity(), R.layout.fragment_tc_authentication, null);
        return mView;
    }


    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initView();
        initEvent();
    }
    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }


    private void initView() {
        mMainRl = (RelativeLayout) mView.findViewById(R.id.main_rl);
        mIvFingerUnlock = (ImageView) mView.findViewById(R.id.iv_finger_unlock);
        mTvFingerUnlock = (TextView) mView.findViewById(R.id.tv_finger_unlock);
        mEtWeight = (ClearEditText) mView.findViewById(R.id.et_weight);
        mSureBtn = (Button) mView.findViewById(R.id.sure_btn);
    }

    private void initEvent() {
        mMainRl.setOnClickListener(this);
        mIvFingerUnlock.setOnClickListener(this);
        mTvFingerUnlock.setOnClickListener(this);
        mSureBtn.setOnClickListener(this);
        mEtWeight.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.length() > 0) {
                    mSureBtn.setBackground(getResources().getDrawable(R.drawable.common_btn1_normal_shape));
                    mSureBtn.setEnabled(true);
                } else {
                    mSureBtn.setBackground(getResources().getDrawable(R.drawable.common_btn1_noclick_shape));
                    mSureBtn.setEnabled(false);
                }
            }
        });
        mEtWeight.setOnEditorActionListener(new TextView.OnEditorActionListener() {

            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                /*判断是否是“GO”键*/
                if (actionId == EditorInfo.IME_ACTION_DONE) {
                    checkPassword(mEtWeight.getText().toString().trim());
                    return true;
                }
                return false;
            }

        });
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.iv_finger_unlock || id == R.id.tv_finger_unlock) {
            showFingerUnlock();
        } else if (id == R.id.sure_btn) {
            checkPassword(mEtWeight.getText().toString().trim());
        } else if (id == R.id.main_rl) {
            hideSoftKeyBoard(mEtWeight);
        }
    }

    @Override
    public void setTitle() {
        if (peekFragment() instanceof TCAuthenticationFragment) {
            mActivity.setTitle(getResources().getString(R.string.authentication));
        }
    }

    @Override
    public void requestDatas() {
        EventBus.getDefault().register(this);
        dialogTools = DialogTools.getInstance();
        authentication();
    }


    //判断是否显示指纹验证功能

    private void authentication() {
        mFingerprintIdentify = new FingerprintIdentify(BaseApplication.getApplicationInstance(), new BaseFingerprint.FingerprintIdentifyExceptionListener() {
            @Override
            public void onCatchException(Throwable exception) {
                LogUtils.showLog(exception.getLocalizedMessage());
            }
        });

        if (!mFingerprintIdentify.isHardwareEnable() || !mFingerprintIdentify.isRegisteredFingerprint()) {
            mIvFingerUnlock.setVisibility(View.GONE);
            mTvFingerUnlock.setVisibility(View.GONE);
            return;
        } else {
            mIvFingerUnlock.setVisibility(View.VISIBLE);
            mTvFingerUnlock.setVisibility(View.VISIBLE);
            showFingerUnlock();

        }
    }
    Handler handler;
    DialogRunnable dialogRunnable;
    private Dialog mDialogFinger;
    //开启指纹解锁
    private void showFingerUnlock() {
        handler = new Handler();
        dialogRunnable = new DialogRunnable();
        handler.postDelayed(dialogRunnable, 200);
        mFingerprintIdentify.startIdentify(3, new BaseFingerprint.FingerprintIdentifyListener() {
            @Override
            public void onSucceed() {
                //指纹识别成功
                mDialogFinger.dismiss();
                startTC();
            }

            @Override
            public void onNotMatch(int availableTimes) {
                LogUtils.showLog("availableTimes: " + availableTimes);
            }

            @Override
            public void onFailed(boolean isDeviceLocked) {
                LogUtils.showLog("onFailed          " + isDeviceLocked);
                mDialogFinger.dismiss();
                toast(mActivity.getResources().getString(R.string.finger_waite));
                handler.removeCallbacks(dialogRunnable);
            }

            @Override
            public void onStartFailedByDeviceLocked() {
                LogUtils.showLog("onStartFailedByDeviceLocked");
                mFingerprintIdentify.cancelIdentify();
                toast(mActivity.getResources().getString(R.string.finger_waite));
                handler.removeCallbacks(dialogRunnable);
            }
        });

    }
    class DialogRunnable implements Runnable {

        @Override
        public void run() {
            dialogTools.showCustomStartFinger(mActivity, true, getResources().getString(R.string.verify_fingerprint), new DialogTools.ConfirmListener() {
                @Override
                public void setConfirmListener(final Dialog dialog, View view, String input) {
                    mDialogFinger = dialog;
                }
            }, new DialogTools.DismissListener() {
                @Override
                public void setDismissListener(Dialog dialog, View view) {
                    dialog.dismiss();
                    mFingerprintIdentify.cancelIdentify();
                }
            });
        }
    }
    private void startTC() {
        hideSoftKeyBoard(mEtWeight);
        TriangulationChainFragment triangulationChainFragment = new TriangulationChainFragment();
        Bundle bundle = new Bundle();
        bundle.putInt("from", 1);//0建立1管理
        if ("CreaterLookCreaterFragment".equals(getArguments().getString("from"))){
            bundle.putString("buId",getArguments().getString("buId"));
        }else{
            CardDeskFunctionResponseBean.TaskBean taskBean = (CardDeskFunctionResponseBean.TaskBean) getArguments().getSerializable(Constant.KEY_CARD_DESK_FUNCTION_DETAILS);
            String buId = taskBean.getBusinessId();
            bundle.putString("buId",buId);
        }
        triangulationChainFragment.setArguments(bundle);
        popFragment();
        pushFragment(triangulationChainFragment);
    }

    /**
     * 密码验证
     */
    private void checkPassword(String password) {
        Map<String, Object> hashMap = new HashMap<String, Object>();
        try {
            byte[] data = RSAUtil.encryptByPublicKey(password.getBytes(), RSAUtil.publicKey);
            password = Base64Utils.encodeBase64(data);
            hashMap.put("password", password);
            NoHttpUtils.httpPost(UserCenterConstant.CHECK_PASSWORD, hashMap, onResponseListener, 0);
            showProgressDialog();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    NoHttpUtils.OnResponseListener onResponseListener = new NoHttpUtils.OnResponseListener() {
        @Override
        public void onSucceed(CommonClass commonClass, int what) {
            switch (what) {
                case 0:
                    if (TextUtils.equals("0", commonClass.getCode())) {
                        startTC();
                    } else {
                        toast(getResources().getString(R.string.password_authentication_failed));
                    }
                    break;
            }
        }

        @Override
        public void onFailed(String result, int what) {
            toast(getResources().getString(R.string.password_authentication_failed));
        }

        @Override
        public void onFinish(int what) {
            dismissProgressDialog();
        }
    };

    public void onEventMainThread(BackListenerEvent event) {
        String message = event.getMsg();
        if (message.equals("TCAuthenticationFragment")) {
            hideSoftKeyBoard(mEtWeight);
            popFragment();
        }
    }
}
